package com.taotao.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.utils.JsonUtils;
import com.taotao.utils.FastDFSClient;

@Controller
public class PictureController {

	@Value("${IMAGE_SERVER_HOST}")
	private String IMAGE_SERVER_HOST;

	@RequestMapping(value="/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8") 
	@ResponseBody
	public String pictureUpload(MultipartFile uploadFile) {
		byte[] fileContent;
		// 创建map，存放返回结果
		Map result = new HashMap<>();
		try {
			// 获取文件内容
			fileContent = uploadFile.getBytes();
			// 获取文件名称
			String filename = uploadFile.getOriginalFilename();
			// 获取文件扩展名
			String extName = filename.substring(filename.lastIndexOf(".") + 1);
			// 创建文件上传客户端
			FastDFSClient fastDFSClient = new FastDFSClient(
					"classpath:resources/fastdfs_client.conf");
			// 上传文件
			String url = fastDFSClient.uploadFile(fileContent, extName);
			// 拼接路径
			String serverUrl = IMAGE_SERVER_HOST + url;

			result.put("error", 0);
			result.put("url", serverUrl);

			// 将map转换为json
			String jsonResult = JsonUtils.objectToJson(result);

			return jsonResult;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.put("error", 1);
			result.put("message", "图片上传失败");
			// 将map转换为json
			String jsonResult = JsonUtils.objectToJson(result);
			return jsonResult;
		}

	}
}
